﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClassObjectPool<T> where T :class, new ()
{
    protected Stack<T> m_Pool = new Stack<T>();
    protected int ObjectCount = 0;//对象数量

    int usedCount = 0;//已经使用的数量
    int desusedCount;//未使用的数量

    /// <summary>
    /// 已经使用的对象数量
    /// </summary>
    public int UsedCount
    {
        get { return usedCount; }
    }

    /// <summary>
    /// 未使用的对象数量
    /// </summary>
    public int DesUsedCount
    {
        get { return desusedCount; }
    }

    /// <summary>
    /// 初始化对象池
    /// </summary>
    /// <param name="count"></param>
    public ClassObjectPool(int count = 10)
    {
        ObjectCount = count;
        desusedCount = ObjectCount - usedCount;
        for (int i = 0; i < 10; i++)
        {
            m_Pool.Push(new T());
        }
    }

    /// <summary>
    /// 获取一个对象
    /// </summary>
    /// <returns></returns>
    public T GetObjectPool(bool createIfPoolEmpty)
    {
        if (m_Pool.Count>0)
        {
            T temp = m_Pool.Pop();
            if (temp == null)
            {
                if (createIfPoolEmpty)
                {
                    
                }
            }
            usedCount++;//已经使用的数量加一
            return temp;
        }
        else
        {
            if (createIfPoolEmpty)
            {
                T rtn = new T();
                usedCount++;
                return rtn;
            }
        }
        return null;
    }

    /// <summary>
    /// 回收一个对象
    /// </summary>
    /// <param name="item"></param>
    public bool RecoveryObject(T item)
    {
        if (item == null)
        {
            return false;
        }
        usedCount--;
        if (m_Pool.Count>= ObjectCount&&m_Pool.Count>0)
        {
            item = null;
            return false;
        }
        m_Pool.Push(item);
        return true;
    }

}
